/**
 * Copyright 2011 Hutrasoft.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var title_tmpl = "%PROJECT% issue updates";
var url_tmpl = "http://%PROJECT%/feeds/posts/default?max-results=4&nocache=0";
var feed_tmpl = "http://%PROJECT%/feeds/posts/default?max-results=4&nocache=0";
var prefs_obj = new gadgets.Prefs();
var projectName_str = "";
var moreandmore = "<center><div class='post-detail-more' id='titleEntryObject_%NUM%'><a class='linkdetail' href='%LINK%' target='_parent' >Chi tiết »</a></div></center>";
var row_tmpl = "<div class='entry-body'><div class='entry-separated' id='postEntryObject_%NUM%'>"+"%SUMMARY%" +moreandmore+"</div><div style='clear: both;'></div></div>";
var sep_str = "";

// Expansion definitions and tracking, see addExpansionEvents()
var MINIMIZED_SUMMARY = 0;
var MAXIMIZED_SUMMARY = 1;
var UNHOVERED_EXPANDER_ARR = ['0 -24px','-12px -24px']
var HOVERED_EXPANDER_ARR = ['0 -36px','-12px -36px']
var stories_arr = new Array();//[MINIMIZED_SUMMARY,MINIMIZED_SUMMARY,MINIMIZED_SUMMARY];

/**
 * Unlike the scraping gadgets, this function doesn't actually render anything; rather,
 * it asks the API to get a feed.  <code>renderCallback</code> is in charge of rendering.
 *
 * @param response_str  The page retrieved by <code>init</code>, unused.
 */
function render(response_str) {
  var feed_url = feed_tmpl.replace("%PROJECT%", projectName_str);
  // Get the feed
  fetchAsDom(feed_url, renderCallback);
}

/**
 * Actually render the content off the feed.
 *
 * @param feed  The JSON feed.
 */
function renderCallback(dom) {
	
  var content_str = "";
  if (!dom.data) {
    content_str += "No issue updates could be found.";
  }
  var arr = new Array();
  var entries = dom.data.getElementsByTagName("entry");
  
	  for (var i = 0; i < entries.length; i++) {
		  try{
				var entry = entries[i];
				var children = entry.childNodes;
				var title="", content="", link="";
				
				for (var j = 0; j < children.length; j++) {
				  var node = children[j];
				  try{
					  if (node.nodeName == "link") {
						  if(node.getAttribute("rel")=="alternate"){
							link =node.getAttribute("href");
						  }
					  }else if (node.nodeName == "title") {
						title = node.firstChild.nodeValue;
					  } else if (node.nodeName == "content") {
						  content = node.firstChild.nodeValue;

                          content = content.substring(0,content.indexOf("<a name='more'>"));
					  } 
				  }catch(e){
				  }
				}
				stories_arr.push(MINIMIZED_SUMMARY);
				var key = "expansion"+String(i);
				    arr.push(key);
				content_str += row_tmpl.replace(/%LINK%/g, link).replace(/%NUM%/g, String(i)).replace(/%SUMMARY%/g, content) + sep_str;

		  }catch(e){

          }
	  }
  // Inject the HTML
  $("#content").html(content_str);

  // Add expansion events (replicating the feed gadget)
  addExpansionEvents();
  //addExpansionEventsAll(arr);

  // Auto-adjust the gadget height
  adjustIFrameHeight();
}

/**
 * Add events for the expansion and collapse of feed items.
 */
function addExpansionEventsAll(arr) {
	for(var i=0;i<arr.length;i++){
		var key = arr[i];
		$("#"+key).click(function(event) {
			event.preventDefault();
			expander(i);
			jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[i] ]);
		});
	}	
	
	for(var i=0;i<arr.length;i++){
		var key = arr[i];
		$("#"+key).hover(function(event) {
		event.preventDefault();
			jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[i] ]);
		  }, function(event) {
			event.preventDefault();
			jQuery(this).css('background-position', UNHOVERED_EXPANDER_ARR[ stories_arr[i] ]);
		});
	}	
}
function addExpansionEvents() {
  // The click events, actually expand / collapse
  $("#expansion0").click(function(event) {
    event.preventDefault();
    expander(0);
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[0] ]);
  });
  $("#expansion1").click(function(event) {
    event.preventDefault();
    expander(1);
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[1] ]);
  });
  $("#expansion2").click(function(event) {
    event.preventDefault();
    expander(2);
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[2] ]);
  });

  // The hover events, UI goodies
  $("#expansion0").hover(function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[0] ]);
  }, function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', UNHOVERED_EXPANDER_ARR[ stories_arr[0] ]);
  });
  $("#expansion1").hover(function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[1] ]);
  }, function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', UNHOVERED_EXPANDER_ARR[ stories_arr[1] ]);
  });
  $("#expansion2").hover(function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', HOVERED_EXPANDER_ARR[ stories_arr[2] ]);
  }, function(event) {
    event.preventDefault();
    jQuery(this).css('background-position', UNHOVERED_EXPANDER_ARR[ stories_arr[2] ]);
  });
}

/**
 * Actually perform the expansion / collapsing.  Called by events assigned in
 * <code>addExpansionEvents</code>.
 *
 * @param story_num The number of the story, should have a corresponding
 *                  <code>#expansionContentXX</code>, where <code>XX</code>
 *                  is <code>story_num</code>
 */
function expander(story_num) {
  if (stories_arr[story_num] == MINIMIZED_SUMMARY) {
    // Maximize
    stories_arr[story_num] = MAXIMIZED_SUMMARY;
    $("#expansionContent" + story_num).show();
    adjustIFrameHeight();
  } else {
    // Minimize
    stories_arr[story_num] = MINIMIZED_SUMMARY;
    $("#expansionContent" + story_num).hide();
    adjustIFrameHeight();
  }
}

gadgets.util.registerOnLoadHandler(init);
